/*******************************************************************************
* CSCI321 Major Project 2010 - University of Wollongong                        *
********************************************************************************
* Program:		WeaveEdit                                              *
* Authors:		Simon Allen (Student#: 3457527, Unix: sa655)           *
*			Scott Bellis (Student#: 3479110, Unix: sjb900)         *
*			Jason Benger (Student#: 3454137, Unix: jb960)          *
*			Timothy Newmarch (Student#: 3459263 Unix: tgn336)      *
*			Benjamin Richardson (Student# 3467752, Unix: bjr401)   *
* Supervisor:		Daniel F. Saffioti                                     *
* Modified:		28/10/2010                                             *
* Description:		WeaveEdit is a highly portable collaborative text      *
*			editor and word processor, allowing several users to   *
*			read and edit multiple documents at the same time.     *
*			It is available for Mac OS X, Windows and Linux,       *
*			utilising Nokia's Qt development framework.            *
*******************************************************************************/


#include <QtEndian>
#include <QSocketNotifier>
#include "bonjourregister.h"

BonjourRegister::BonjourRegister(QObject *parent) : QObject(parent)
{
	serviceRef = NULL;
}

BonjourRegister::~BonjourRegister()
{
	if (serviceRef)
		DNSServiceRefDeallocate(serviceRef);
}

void BonjourRegister::registerService(QString name, QString type, quint16 port)
{
	if (serviceRef)
		return;

	port = qToBigEndian(port);

	//register the service
	DNSServiceErrorType error;
	error = DNSServiceRegister(&serviceRef, 0, 0, name.toAscii().constData(),
							  type.toAscii().constData(), NULL, NULL, port, 0, NULL, registerCallback, this);

	if (error != kDNSServiceErr_NoError)
	{
		emit bonjourError();
		return;
	}

	//get the socket descriptor and wait for replies
	int sock = DNSServiceRefSockFD(serviceRef);

	if (sock == -1)
	{
		emit bonjourError();
		return;
	}

	//monitor the socket for new info
	QSocketNotifier *notify = new QSocketNotifier(sock, QSocketNotifier::Read, this);
	connect(notify, SIGNAL(activated(int)), this, SLOT(receiveSomeInfo(int)));
}

void BonjourRegister::receiveSomeInfo(int)
{
	DNSServiceProcessResult(serviceRef);	//calls the callback
}

void BonjourRegister::registerCallback(DNSServiceRef ref, DNSServiceFlags flags, DNSServiceErrorType error,
									   const char *name, const char *type, const char *domain, void *context)
{
	if (error != kDNSServiceErr_NoError)
		emit ((BonjourRegister*)context)->bonjourError();
}
